package com.yxp423.ssmempl.service.impl;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yxp423.ssmempl.bean.EmplLog;
import com.yxp423.ssmempl.bean.Project;
import com.yxp423.ssmempl.bean.User;
import com.yxp423.ssmempl.mapper.EmplLogMapper;
import com.yxp423.ssmempl.mapper.ProjectMapper;
import com.yxp423.ssmempl.mapper.UserMapper;
import com.yxp423.ssmempl.service.IEmplLogService;
import com.yxp423.ssmempl.utils.base.AjaxResult;
import com.yxp423.ssmempl.utils.consts.ApplyConst;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Description: java类作用描述
 * @Author: yxp
 * @CreateDate: 2019-05-24 21:12
 * @Version: 1.0
 */
@Service
public class EmplLogService implements IEmplLogService {

	@Autowired
	EmplLogMapper emplLogMapper;
	@Autowired
	ProjectMapper projectMapper;
	@Autowired
	UserMapper userMapper;

	Cache<String, User> userCache = CacheUtil.newLRUCache(10, DateUnit.MINUTE.getMillis() * 5);
	Cache<String, Project> projectCache = CacheUtil.newLRUCache(10, DateUnit.MINUTE.getMillis() * 5);


	@Override
	public AjaxResult saveEmplLog(EmplLog emplLog) {

		AjaxResult result = new AjaxResult();

		if (ObjectUtil.isNull(emplLog)) {

			result.setSuccess(false);
			result.setMsg("前台传入数据失败");
			return result;
		}
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		if (ObjectUtil.isNull(user)) {
			result.setSuccess(false);
			result.setMsg("请登录");
			return result;
		}
		if (!StrUtil.equals(user.getUserId().toString(), emplLog.getUserId())) {

			result.setSuccess(false);
			result.setMsg("申请人只能为自己");
			return result;
		}


		try {
			emplLog.setCreateTime(DateUtil.date());
			emplLog.setReviewStatus(ApplyConst.STATUS_CHECKING);

//			DateUtil.parse(emplLog.getLogTime());
			int flag = emplLogMapper.insert(emplLog);
			if (flag > 0) {

				result.setSuccess(true);
				result.setMsg("提交成功");
			} else {
				result.setSuccess(false);
				result.setMsg("提交失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg("发生错误，错误信息" + e.toString());
		}

		return result;
	}

	@Override
	@Transactional(readOnly = true)
	public AjaxResult getEmplLog() {

		AjaxResult result = new AjaxResult();

		User user = (User) SecurityUtils.getSubject().getPrincipal();
		if (ObjectUtil.isNull(user)) {

			result.setSuccess(false);
			result.setMsg("请登录");
			return result;

		}

		try {
//			QueryWrapper<EmplLog> wrapper = new QueryWrapper<>();
//			List<EmplLog> emplLogList = emplLogMapper.selectList(wrapper
//					.eq("user_id", user.getUserId().toString())
//					.eq("DATE_FORMAT(log_time,'%Y%M')", "DATE_FORMAT(CURDATE(),'%Y%M')"));
			List<EmplLog> emplLogList = emplLogMapper.selectMyEmplLog(user);

			for (EmplLog emplLog : emplLogList) {

				if (ObjectUtil.isNull(projectCache.get("project" + emplLog.getProjectId()))) {

					Project project = projectMapper.selectById(emplLog.getProjectId());
					emplLog.setProjectName(project.getProjectName());
					projectCache.put("project" + emplLog.getProjectId(), project);
				} else {
					emplLog.setProjectName(projectCache.get("project" + emplLog.getProjectId()).getProjectName());
				}


				if (ObjectUtil.isNull(userCache.get("user" + emplLog.getReviewerId()))) {

					User user1 = userMapper.getUserById(Integer.parseInt(emplLog.getReviewerId()));
					userCache.put("user" + emplLog.getReviewerId(), user1);
					emplLog.setReviewerName(user1.getName());

				} else {

					emplLog.setReviewerName(userCache.get("user" + emplLog.getReviewerId()).getName());

				}


				if (ObjectUtil.isNull(userCache.get("user" + emplLog.getUserId()))) {
					User user2 = userMapper.getUserById(Integer.parseInt(emplLog.getUserId()));
					userCache.put("user" + emplLog.getUserId(), user2);
					emplLog.setUserName(user2.getName());
				} else {

					emplLog.setUserName(userCache.get("user" + emplLog.getUserId()).getName());

				}
			}

			if (ObjectUtil.isNotEmpty(emplLogList)) {
				result.setSuccess(true);
				result.setData(emplLogList);

			} else {
				result.setSuccess(false);
				result.setMsg("列表为空");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg("错误信息为" + e.toString());
			return result;
		}

		return result;
	}

	@Override
	public AjaxResult deleteEmplLog(EmplLog emplLog) {
		AjaxResult result = new AjaxResult();
		User user = (User) SecurityUtils.getSubject().getPrincipal();

		if (ObjectUtil.isNull(user)) {
			result.setSuccess(false);
			result.setMsg("请登录");
			return result;
		}

		try {
			EmplLog selectById = emplLogMapper.selectById(emplLog.getLogId());

			if (StrUtil.equals(selectById.getReviewStatus(), ApplyConst.STATUS_CHECKING)) {

				int flag = emplLogMapper.deleteById(emplLog.getLogId());
				if (flag > 0) {

					result.setSuccess(true);
					result.setMsg("删除成功");
				}
			} else {

				result.setSuccess(false);
				result.setMsg("已经审核，不能删除");

			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg("错误，信息为" + e.toString());
		}

		return result;
	}

	@Override
	public AjaxResult getMyReviewLogs(EmplLog emplLog) {

		AjaxResult result = new AjaxResult();
		User user = (User) SecurityUtils.getSubject().getPrincipal();

		if (ObjectUtil.isNull(user)) {
			result.setSuccess(false);
			result.setMsg("请登录");
			return result;
		}

		try {
			List<EmplLog> emplLogList = emplLogMapper.selectList(
					new QueryWrapper<EmplLog>()
							.eq("user_id", emplLog.getUserId())
							.eq("reviewer_id", user.getUserId()));

			if (ObjectUtil.isNotEmpty(emplLogList)) {


				for (EmplLog log : emplLogList) {

					if (ObjectUtil.isEmpty(userCache.get("user" + log.getUserId()))) {

						User userById = userMapper.getUserById(Integer.parseInt(log.getUserId()));
						log.setUserName(userById.getName());
						userCache.put("user" + log.getUserId(), userById);

					} else {

						log.setUserName(userCache.get("user" + log.getUserId()).getName());
					}
					if (ObjectUtil.isEmpty(userCache.get("user" + log.getReviewerId()))){

						User userById = userMapper.getUserById(Integer.parseInt(log.getReviewerId()));
						log.setReviewerName(userById.getName());
						userCache.put("user"+log.getReviewerId(),userById);
					}else {
						log.setReviewerName(userCache.get("user"+log.getReviewerId()).getName());
					}
					if (ObjectUtil.isEmpty(projectCache.get("project"+log.getProjectId()))){

						Project project = projectMapper.selectById(log.getProjectId());
						log.setProjectName(project.getProjectName());
						projectCache.put("project"+log.getProjectId(),project);
					}else {
						log.setProjectName(projectCache.get("project"+log.getProjectId()).getProjectName());
					}

				}
				result.setSuccess(true);
				result.setMsg("获取成功，共有"+emplLogList.size()+"条数据");
				result.setData(emplLogList);
			}else {
				result.setSuccess(false);
				result.setMsg("数据为空");
				return result;
			}


		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg("发生错误,信息为" + e.toString());
			return result;
		}


		return result;
	}

	@Override
	@Transactional(rollbackFor = RuntimeException.class)
	public AjaxResult reviewLog(EmplLog emplLog) {
		AjaxResult result = new AjaxResult();

		User user = (User) SecurityUtils.getSubject().getPrincipal();

		if (ObjectUtil.isNull(user)){

			result.setSuccess(false);
			result.setMsg("请登录");
			return result;
		}


		try {


			EmplLog log = emplLogMapper.selectById(emplLog.getLogId());
			if (!StrUtil.equals(log.getReviewStatus(),ApplyConst.STATUS_CHECKING)){//审核状态不是“审核中”

				result.setSuccess(false);
				result.setMsg("该日志已审核");
				return result;

			}

			if (!StrUtil.equals(log.getReviewerId(),user.getUserId().toString())){

				result.setSuccess(false);
				result.setMsg("审核人不是你");
				return result;

			}

			emplLog.setVersion(log.getVersion());
			emplLog.setReviewTime(DateUtil.date());

			int flag = emplLogMapper.updateById(emplLog);

			if (flag>0){

				result.setSuccess(true);
				result.setMsg("审核成功");



			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg("失败，信息为"+e.toString());
		}


		return result;
	}


}
